<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增采购单')"/>
    <th:block th:include="include :: bootstrap-editable-css"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-supplier-order-add">
        <div class="form-group">
            <label class="col-sm-2 control-label"><span style="color: red; ">*</span>采购标题：</label>
            <div class="col-sm-6">
                <input class="form-control" type="text" name="orderTitle" id="orderTitle" required>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label"><span style="color: red; ">*</span>选择供应商：</label>
            <div class="col-sm-6">
                <div class="input-group">
                    <input type="hidden" name="supplierId">
                    <input type="text" class="form-control" id="supplierBox" required>
                    <div class="input-group-btn">
                        <button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown">
                            <span class="caret"></span>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        <div class="form-group" id="productListTable">
            <label class="col-sm-2 control-label"><span style="color: red; ">*</span>商品清单：</label>
            <div class="col-sm-10">
                <div class="btn-group-sm" id="toolbar" role="group">
                    <a class="btn btn-success" onclick="insertRow()">
                        <i class="fa fa-plus"></i> 新增
                    </a>
                </div>
                <div class="select-table table-striped">
                    <table id="bootstrap-table"></table>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label"><span style="color: red; ">*</span>合计金额：</label>
            <div class="col-sm-2">
                <div class="input-group">
                    <span class="input-group-addon">¥</span>
                    <input class="form-control" type="number" value="0.00" name="totalAmount" id="totalAmount" readonly>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label"><span style="color: red; ">*</span>应付金额：</label>
            <div class="col-sm-2">
                <div class="input-group">
                    <span class="input-group-addon">¥</span>
                    <input class="form-control" type="number" value="0.00" name="payAmount" id="payAmount"
                           placeholder="付款金额以该为准" required>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label"><span style="color: red; ">*</span>最迟到货日期</label>
            <div class="col-sm-3">
                <div class="input-group date">
                    <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                    <input type="text" class="form-control time-input" id="deadline" placeholder="请输入最迟到货日期"
                           name="deadline" required/>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">备注：</label>
            <div class="col-sm-3">
                <textarea class="form-control" type="text" name="remark"></textarea>
            </div>
        </div>
    </form>
</div>
<div class="row">
    <div class="col-sm-offset-5 col-sm-10">
        <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i class="fa fa-check"></i>新 增
        </button>&nbsp;
        <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i class="fa fa-reply-all"></i>关 闭
        </button>
    </div>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: bootstrap-suggest-js"/>
<th:block th:include="include :: bootstrap-table-editable-js"/>


<script type="text/javascript">
    var prefix = ctx + "back/supplierOrder";
    let orderNum = 1;
    $('#productListTable').hide();
    var options = {
        showSearch: false,
        showRefresh: false,
        showToggle: false,
        showColumns: false,
        pagination: false,
        uniqueId: "orderNum",
        onEditableSave: onEditableSave,
        height: 350,
        columns: [
            {
                field: 'orderNum',
                title: '排序',
            },
            {
                field: 'productId',
                title: '商品ID',
                visible: false,
            },
            {
                field: 'productName',
                title: '商品名称',
                formatter: function (value, row, index) {
                    return '<a href="javascript:void(0)" onclick="selectProductTree(' + row.orderNum + ')" class="editable editable-click">' + value + '</a>'
                }
            },
            {
                field: 'productSkuId',
                title: '规格ID',
                visible: false
            },
            {
                field: 'productSkuCode',
                title: '规格code',
                visible: false,
            },
            {
                field: 'productSkuName',
                title: '规格名称',
                visible: false,
                formatter: function (value, row, index) {
                    return '<a href="javascript:void(0)" onclick="selectProductSku(' + row.orderNum + ')" class="editable editable-click">' + value + '</a>'
                }
            },
            {
                field: 'productSkuPrice',
                title: '单价',
                width: '15%',
                visible: false,
                editable: {
                    type: 'text',
                    title: '单价',
                    emptytext: "【单价】不能为空",
                    validate: function (v) {
                        if ($.trim(v) == '') {
                            return '【单价】不能为空!';
                        }
                        if (isNaN(v)) {
                            return '【单价】必须是数字';
                        }
                        if (!(/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(v))) {
                            return '请输入正确的【单价】';
                        }
                    }
                }
            },
            {
                field: 'productQuantity',
                title: '数量',
                width: '10%',
                visible: false,
                editable: {
                    type: 'text',
                    title: '数量',
                    emptytext: "【数量】不能为空",
                    validate: function (v) {
                        if ($.trim(v) == '') {
                            return '【数量】不能为空!';
                        }
                        if (isNaN(v)) {
                            return '【数量】必须是数字';
                        }
                        if (!(/(^[1-9]\d*$)/.test(v))) {
                            return '请输入正确的【数量】';
                        }
                    }
                }
            },
            {
                field: 'productPrice',
                title: '合计金额',
                width: '15%',
                editable: {
                    type: 'text',
                    title: '合计金额',
                    emptytext: "【合计金额】不能为空",
                    validate: function (v) {
                        if ($.trim(v) == '') {
                            return '【合计金额】不能为空!';
                        }
                        if (isNaN(v)) {
                            return '【合计金额】必须是数字';
                        }
                        if (!(/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(v))) {
                            return '请输入正确的【合计金额】';
                        }
                    }
                }
            },
            {
                field: 'remark',
                title: '备注',
                editable: {
                    type: 'text',
                    title: '备注',
                }
            },
            {
                title: '操作',
                align: 'center',
                formatter: function (value, row, index) {
                    var actions = [];
                    actions.push('<a class="btn btn-danger btn-xs" href="#" onclick="removeRow(\'' + row.orderNum + '\')"><i class="fa fa-remove">删除</i></a> ');
                    return actions.join('');
                }
            }
        ]
    };
    $.table.init(options);

    /* 商品清单新增 */
    function insertRow() {
        $("#" + table.options.id).bootstrapTable('insertRow', {
            index: 0, // 你想插入到哪，0表示第一行
            row: {
                productId: 0,
                orderNum: orderNum++,
                productName: "请选择",
                productSkuId: 0,
                productSkuName: "请选择",
                productSkuPrice: 0,
                productSkuCalVal: 0.0,
                productQuantity: 0,
                productPrice: 0,
                remark: "无"
            }
        })
    }

    /* 商品清单删除 */
    function removeRow(orderNum) {
        $.modal.confirm("确定要删除该种商品吗？", function() {
            $("#" + table.options.id).bootstrapTable('removeByUniqueId', orderNum)
        });
    }

    /* 下单商品选择 */
    function selectProductTree(orderNum) {
        var url = ctx + "back/product/tree";
        var options = {
            title: '下单商品选择',
            width: "380",
            url: url,
            callBack: function (index, layero) {
                var tree = layero.find("iframe")[0].contentWindow.$._tree;
                if ($.tree.onlyAllowOneLevel(tree, 2)) {
                    var body = layer.getChildFrame('body', index);
                    var productId = body.find('#treeId').val();
                    var productName = body.find('#treeName').val();
                    $("#" + table.options.id).bootstrapTable("showColumn", "productSkuName");
                    $("#" + table.options.id).bootstrapTable('updateByUniqueId', {
                        id: orderNum,
                        row: {
                            productId: productId / 10000,
                            productName: productName,
                            productSkuName: "请选择",
                        }
                    });
                    layer.close(index);
                }
            }
        };
        $.modal.openOptions(options);
    }

    /* 商品sku选择 */
    function selectProductSku(orderNum) {
        let rows = $("#" + table.options.id).bootstrapTable('getRowByUniqueId', orderNum);
        let url = ctx + "back/productSkuStock/forOrderList/" + rows.productId;
        let options = {
            title: '下单商品Sku选择',
            width: "800",
            url: url,
            callBack: function (index) {
                var body = layer.getChildFrame('body', index);
                var productSkuId = body.find('#skuId').val();
                var productSkuCode = body.find('#productSkuCode').val();
                var productSkuName = body.find('#productSkuName').val();
                var productSkuPrice = body.find('#productSkuPrice').val();
                var productSkuCalVal = body.find('#productSkuCalVal').val();
                $("#" + table.options.id).bootstrapTable('updateByUniqueId', {
                    id: orderNum,
                    row: {
                        productSkuId: productSkuId,
                        productSkuCode: productSkuCode,
                        productSkuName: productSkuName,
                        productSkuPrice: productSkuPrice,
                        productSkuCalVal: productSkuCalVal,
                    }
                });
                $("#" + table.options.id).bootstrapTable("showColumn", "productQuantity");
                $("#" + table.options.id).bootstrapTable("showColumn", "productSkuPrice");
                $("#" + table.options.id).bootstrapTable("showColumn", "productPrice");
                calTotalAmount();
                layer.close(index);
            }
        };
        $.modal.openOptions(options);
    }

    //修改单价
    //修改数量
    //修改合计
    //修改备注
    function onEditableSave(field, row, oldValue, $el) {
        //TODO：计算该行的总价格
        let productPrice = row.productPrice;
        switch (field) {
            case 'productSkuPrice':
            case 'productQuantity':
                productPrice = parseFloat(row.productSkuPrice) * parseInt(row.productQuantity);
                break;
            default:
                break;
        }
        $("#" + table.options.id).bootstrapTable('updateByUniqueId', {
            id: row.orderNum,
            row: {
                productPrice: toDecimal(productPrice),
            }
        });
        //TODO：计算订单总价格
        calTotalAmount();
    }

    function calTotalAmount() {
        let totalAmount = 0;
        let productObj = $("#" + table.options.id).bootstrapTable('getData');
        for (let i = 0; i < productObj.length; i++) {
            totalAmount += parseFloat(productObj[i].productPrice);
        }
        $('#totalAmount').val(toDecimal(totalAmount));
    }

    function toDecimal(x) {
        var f = parseFloat(x);
        if (isNaN(f)) {
            return;
        }
        f = Math.round(x * 100) / 100;
        return f;
    }

    // $("#form-supplier-order-add").validate({
    //     onkeyup: false,
    //     rules: {
    //         orderTitle: {
    //             remote: {
    //                 url: prefix + "/checkOrderTitleUnique",
    //                 type: "post",
    //                 dataType: "json",
    //                 data: {
    //                     "orderTitle": function () {
    //                         return $.common.trim($("#orderTitle").val());
    //                     },
    //                 },
    //                 dataFilter: function (data, type) {
    //                     return $.validate.unique(data);
    //                 }
    //             }
    //         },
    //         orderNum: {
    //             digits: true
    //         },
    //     },
    //     messages: {
    //         "orderTitle": {
    //             remote: "采购单已存在，请勿重复添加"
    //         }
    //     },
    //     focusCleanup: true
    // });

    //选择供应商
    $("#supplierBox").bsSuggest({
        indexId: 1,
        indexKey: 0,
        keyField: "generalInfo",
        hideOnSelect: true,
        emptyTip: '<b>没有找到供应商信息</b>',
        effectiveFields: ["companyCode", "companyNameAlias", "contactsName", "contactsMobile"],
        effectiveFieldsAlias: {
            companyCode: "供应商编号",
            companyNameAlias: "供应商简称",
            contactsName: "负责人",
            contactsMobile: "负责人手机号",
        },
        data: {
            'value': (function () {
                var list = '';    // 先定义个值，方便下面赋值
                $.ajax({
                    type: 'post',
                    url: ctx + "back/supplier/searchGeneralList",
                    dataType: 'json',
                    data: {
                        pageSize: 1000,
                        orderByColumn: "order_num asc"
                    },
                    async: false,
                    success: function (result) {
                        if (result.code == web_status.SUCCESS) {
                            list = result.rows;
                        } else {
                            $.modal.alert(result.msg);
                        }
                    }
                });
                return list;
            })()
        }
    }).on('onSetSelectValue', function (e, keyword, data) {
        $('input[name="supplierId"]').val(data.supplierId);
        $('#productListTable').show();
    });


    function submitHandler() {
        if ($.validate.form()) {
            let dataArr = $('#form-supplier-order-add').serializeArray();
            let data = {};
            let name ="";
            for (let i = 0; i < dataArr.length; i++) {
                name = dataArr[i].name;
                data[name] = dataArr[i].value
            }
            let productObj = $("#" + table.options.id).bootstrapTable('getData');
            data.productListStr = JSON.stringify(productObj);
            $.operate.save(prefix + "/add", data);
        }
    }
</script>
</body>
</html>
